<template>
  <div style="padding: 20px">
    <el-form>
      <el-form-item label="账户列表" style="margin-bottom: 10px">
        <el-button
          style="color: #fff; background-color: #586cb1; border-color: #586cb1"
          size="mini"
          @click="addAccount({})"
          >添加账户</el-button
        >
      </el-form-item>
    </el-form>
    <!-- table表格：展示用户信息的地方 -->
    <el-table
      :header-cell-style="{ background: '#ececf1', color: '#636870' }"
      border
      style="width: 100%"
      :data="userInfo"
    >
      <el-table-column label="序号" width="80" align="center"
        ><template v-slot="{ $index }">
          <span>{{ (page - 1) * limit + $index + 1 }}</span>
        </template></el-table-column
      >
      <el-table-column
        align="center"
        prop="username"
        label="账户名"
        width="150"
      />
      <el-table-column align="center" prop="roles" label="权限" key="col">
        <template slot-scope="{ row }">
          <div v-if="row.roles">
            <el-tag
              v-for="(role, index) in row.roles.split(',')"
              :key="index"
              type="primary"
              >{{ role }}</el-tag
            >
          </div>
          <div v-else>
            <el-tag
              type="warning"
              style="cursor: pointer"
              @click="updateAccountBtn(row)"
              >此用户没有权限，请点击我去添加权限
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="230" align="center" key="column">
        <template slot-scope="{ row }">
          <el-button
            type="warning"
            size="mini"
            icon="el-icon-edit"
            title="修改用户"
            :disabled="row.username === 'admin'"
            @click="updateAccountBtn(row)"
          />
          <el-button
            style="margin-left: 10px"
            slot="reference"
            type="danger"
            size="small"
            icon="el-icon-delete"
            title="删除用户"
            :disabled="row.username === 'admin'"
            @click="deleteAccountBtn(row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      style="text-align: center; margin-top: 15px"
      :current-page="page"
      :page-sizes="[5, 10, 15, 20, total]"
      :page-size="limit"
      layout="prev, pager, next, jumper, ->, total, sizes"
      :total="total"
      @size-change="handleLimit"
      @current-change="handleCurrentChange"
    />
    <!-- 对话框 :before-close="dialogBeforeClose" -->
    <el-dialog
      :title="form.id ? '修改账户' : '添加账户'"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
      width="width"
    >
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item
          label="账户"
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input
            v-model.trim="form.username"
            clearable
            size="mini"
            placeholder="请输入账户"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          :label-width="formLabelWidth"
          prop="password"
        >
          <el-input
            v-model.trim="form.password"
            clearable
            size="mini"
            placeholder="请输入账户密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="权限" :label-width="formLabelWidth">
          <el-checkbox-group
            key="form.id"
            v-if="form.roles"
            v-model="form.roles"
          >
            <el-checkbox
              :disabled="form.username == 'admin'"
              label="超级管理员"
            ></el-checkbox>
            <el-checkbox label="教师"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateAccount">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import roleApi from "@/api/role";

export default {
  data() {
    return {
      userInfo: [],
      form: {},
      total: 0,
      page: 1,
      limit: 5,
      // 控制添加用户对话框显示
      dialogFormVisible: false,
      // 控制表单宽度
      formLabelWidth: "120px",
      //表单校验
      rules: {
        username: [
          {
            min: 5,
            max: 8,
            message: "长度应为 5 到 8 个字符",
            trigger: "blur",
          },
          { required: true, message: "请输入账户名称", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入账户密码", trigger: "blur" },
          {
            min: 6,
            max: 12,
            message: "长度应为 6 到 12 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.getAccountInfo();
  },
  methods: {
    //获取账户信息
    getAccountInfo() {
      roleApi
        .getAccount({
          page: this.page,
          pageSize: this.limit,
        })
        .then((res) => {
          this.userInfo = res.data;
          this.total = res.total;
        });
    },
    //修改账户信息
    updateAccountBtn(row) {
      this.dialogFormVisible = true;
      let newRow = { ...row };
      // 将目标账户权限分割为数组进行存储
      newRow.roles = row.roles.split(",");
      this.form = newRow;
    },
    // 添加或修改账户信息
    addOrUpdateAccount() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          //判断是否有id
          if (this.form.id) {
            roleApi
              .updateAccount(this.form)
              .then((res) => {
                this.$message.success(res.msg);
                this.getAccountInfo();
                this.form = {};
              })
              .catch((error) => {});
          } else {
            roleApi
              .addAccount(this.form)
              .then((res) => {
                this.$message.success(res.msg);
                this.getAccountInfo();
              })
              .catch((error) => {});
          }
          //关闭对话框
          this.dialogFormVisible = false;
          //清空表单
          this.form = {};
          //重新加载账户信息
          this.getAccountInfo();
        } else {
          this.$message.error('请检查输入')
        }
      });
    },
    // 分页器，
    handleLimit(size) {
      this.limit = size;
      this.getAccountInfo();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.getAccountInfo();
    },
    //删除账户
    deleteAccountBtn(row) {
      this.$confirm("此操作将删除该账户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          roleApi.deleteAccount(row.id).then((res) => {
            this.$message.success(res.msg);
            this.getAccountInfo();
          });
        })
        .catch(() => {});
    },
    //打开添加账户页面
    addAccount(row) {
      this.dialogFormVisible = true;
      let newRow = { ...row };
      // 将目标账户权限分割为数组进行存储
      newRow.roles = ["教师"];
      this.form = newRow;
    },
    //关闭对话框
    handleClose() {
      this.dialogFormVisible = false;
      this.$refs.form.clearValidate();
    },
  },
};
</script>

<style scoped>
#container {
  padding: 20px;
}

/*
  el-table样式穿透 表格居中
*/
::v-deep .el-table th > .cell {
  text-align: center;
}

::v-deep .el-table .cell {
  text-align: center;
}
</style>